﻿using Inovout.Account.Web.Filters;
using Inovout.RedictUrls;
using Inovout.Web.Mvc;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Security.Policy;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace Inovout.Account.Web.Controllers
{
    [AllowAnonymous]
    public class GoController : BaseController
    {

        public override ActionResult Index()
        {

            var requestUrl = this.Request.Url.ToString();
            return RedirectToAction("VerifyUrl", new { url = requestUrl });
        }

        public ActionResult VerifyUrl(string url)
        {
            var refer = this.Request.UrlReferrer;

            IRedictUrlService redictUrlServcie = Inovout.ComponentRegistry.Resolve<IRedictUrlService>();
            RedirctUrl redirctUrl = redictUrlServcie.FindByActionUrl(url);

            //当前时间在有效验证时间范围内
            if (redirctUrl == null || DateTime.Now < redirctUrl.ValidStartTime || DateTime.Now > redirctUrl.ValidEndTime)
            {
                return RedirectToAction("Message", new { messageType = MessageType.Failed, message = Url.Encode("此链接已失效") });
            }
            //次数是否已超出了最大限制
            if (redirctUrl.LimitNumber <= redirctUrl.ValidNumber)
            {
                return RedirectToAction("Message", new { messageType = MessageType.Failed, message = Url.Encode("此链接已失效") });
            }
            //为原始Url添加参数：时间、MD5(CIP+当前时间戳)
            string currentTimeStamp = ConvertDateTimeInt(DateTime.Now).ToString();
            string key = MD5Encoding(GetLocalhostIp() + currentTimeStamp);
            return Redirect(redirctUrl.OrginalUrl + "&key=" + key + "&datetime=" + currentTimeStamp + "&actionurl=" + url);

        }

        private string GetLocalhostIp()
        {
            String strHostName = string.Empty;
            // Getting Ip address of local machine...
            // First get the host name of local machine.
            strHostName = Dns.GetHostName();
            Console.WriteLine("Local Machine's Host Name: " + strHostName);
            // Then using host name, get the IP address list..
            IPHostEntry ipEntry = Dns.GetHostEntry(strHostName);
            IPAddress[] addr = ipEntry.AddressList;
            return addr[0].ToString();
        }

        /// <summary>
        /// DateTime时间格式转换为Unix时间戳格式
        /// </summary>
        /// <param name="time"> DateTime时间格式</param>
        /// <returns>Unix时间戳格式</returns>
        private int ConvertDateTimeInt(System.DateTime time)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            return (int)(time - startTime).TotalSeconds;
        }

        /// <summary>
        /// MD5 加密字符串
        /// </summary>
        /// <param name="rawPass">源字符串</param>
        /// <returns>加密后字符串</returns>
        private string MD5Encoding(string rawPass)
        {
            // 创建MD5类的默认实例：MD5CryptoServiceProvider
            MD5 md5 = MD5.Create();
            byte[] bs = Encoding.UTF8.GetBytes(rawPass);
            byte[] hs = md5.ComputeHash(bs);
            StringBuilder sb = new StringBuilder();
            foreach (byte b in hs)
            {
                // 以十六进制格式格式化
                sb.Append(b.ToString("x2"));
            }
            return sb.ToString();
        }
    }
}